package com.example.springinaction.loadvalue;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;

/**
 * 运行时值注入方式之一 : 属性占位符 Property PlaceHolder
 */
@Configuration
@PropertySource("classpath:app.properties")
public class LoadValueByProp {

    @Autowired
    private Environment environment;



    public void loadValue01(){
        String code = environment.getProperty("code");
        String name = environment.getProperty("name");
    }

    public void loadValueByDefault(){
        String code = environment.getProperty("code","abc");
        String name = environment.getProperty("name","name1");
    }

    public void loadValue02(){
        String countStr = environment.getProperty("count");
        Integer count1 = Integer.parseInt(countStr);

        int count = environment.getProperty("count",Integer.class,0);
    }

    @Value("${code}")
    private String code1;

    @Value("${name}")
    private String name1;

    /**
     * 为了使用占位符,我们必须要配置一个PropertyPlaceholderConfigurer或者PropertySourcesPlaceholderConfigurer的bean.
     * 推荐使用PropertySourcesPlaceholderConfigurer,它能够给予Spring Environment及其属性源来解析占位符.
     * @return
     */
    @Bean
    public static PropertySourcesPlaceholderConfigurer placeholderConfigurer(){
        return new PropertySourcesPlaceholderConfigurer();
    }
}
